package com.imyuanma.qingyun.common.core.structure.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 树构造器
 *
 * @author wangjy
 * @date 2022/05/01 20:50:05
 */
public class TreeBuilder {
    /**
     * 构造树
     *
     * @param treeNodeList 待构造树的数据集, 不允许id重复
     * @return 树结构
     */
    public static <E extends ITreeNode<T>, T> List<E> buildTree(List<E> treeNodeList) {
        if (treeNodeList == null) {
            return null;
        }
        Map<T, E> map = treeNodeList.stream().collect(Collectors.toMap(ITreeNode::nodeId, item -> item));
        List<E> list = new ArrayList<>();
        for (E treeNode : treeNodeList) {
            if (treeNode.parentNodeId() != null) {
                // 当前节点的父亲
                ITreeNode<T> parent = map.get(treeNode.parentNodeId());
                if (parent != null) {
                    parent.appendChildren(treeNode);
                    continue;
                }
            }
            // 找不到父亲的作为根节点
            list.add(treeNode);
        }
        return list;
    }
}
